//
//  AddressBookPerson.m
//  TestAB
//
//  Created by Hunk on 12-2-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AddressBookPerson.h"

@interface AddressBookPerson (Private)

- (NSString*)personLabelName:(NSString*)labelName;

@end

@implementation AddressBookPerson
@synthesize record   = _record;
@synthesize recordID = _recordID;
@synthesize selected = _selected;

- (id)initWithRecord:(ABRecordRef)record
{
    if((self = [super init]))
    {
        _record   = record;
        
        _selected = NO;
    }
    return self;
}

#pragma mark -
#pragma mark record
- (ABRecordRef)record
{
    return _record;
}

- (ABRecordID)recordID
{
    return ABRecordGetRecordID(_record);
}

- (void)setSelected:(BOOL)selected
{
    if(_selected != selected)
    {
        _selected = selected;
    }
}

#pragma mark -
#pragma mark Get person name (FirstName + MiddleName + LastName)
- (NSString *)personName
{
    if(_record)
    {
        NSString *firstName  = (NSString *)ABRecordCopyValue(_record, kABPersonFirstNameProperty);
        NSString *middleName = (NSString *)ABRecordCopyValue(_record, kABPersonMiddleNameProperty);
        NSString *lastName   = (NSString *)ABRecordCopyValue(_record, kABPersonLastNameProperty);

        NSString *nameType = NSLocalizedString(@"命名方式", nil);
        
        if([nameType isEqualToString:@"CN-S"] || [nameType isEqualToString:@"CN-T"])
        {
            return [NSString stringWithFormat:@"%@%@%@", 
                    lastName   ? lastName : @"",
                    middleName ? middleName : @"", 
                    firstName  ? firstName : @""];
        }
        else
        {
            return [NSString stringWithFormat:@"%@%@%@", 
                    firstName  ? firstName : @"", 
                    middleName ? [NSString stringWithFormat:@"%@%@", @"   ", middleName] : @"", 
                    lastName   ? [NSString stringWithFormat:@"%@%@", @"   ", lastName] : @""];
        }
    }
    
    return nil;
}

#pragma mark -
#pragma mark Get person photo
- (UIImage *)personPhoto
{
    if(_record)
    {
        if(ABPersonHasImageData(_record))
        {   
            CFDataRef photoData = ABPersonCopyImageDataWithFormat(_record, kABPersonImageFormatThumbnail);
            
            UIImage *image = [UIImage imageWithData:(NSData*)photoData];
            
            CFRelease(photoData);
            
            return image;
        }
    }
    
    return nil;
}

#pragma mark -
#pragma mark Get person phone number(s)
- (NSDictionary *)personPhone
{
    if(_record)
    {
        ABMultiValueRef phoneNumbers = ABRecordCopyValue(_record, kABPersonPhoneProperty);
        
        NSMutableDictionary* phoneNumbersDic = [[NSMutableDictionary alloc] init];
        
        int nPhoneNumberCount = ABMultiValueGetCount(phoneNumbers);
        
        for(int i = 0; i < nPhoneNumberCount; i++)
        {
            NSString* labelName = [self personLabelName:(NSString*)ABMultiValueCopyLabelAtIndex(phoneNumbers, i)];
            
            NSString* phoneNumberString = (NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, i);
            
            if(![labelName isEqualToString:@"其他:"])
            {
                [phoneNumbersDic setObject:phoneNumberString forKey:labelName];
            }
            else
            {
                if([[phoneNumbersDic allKeys] containsObject:@"其他:"])
                {
                    NSMutableArray* tempArray = [[NSMutableArray alloc] init];
                    
                    [tempArray addObjectsFromArray:[phoneNumbersDic objectForKey:labelName]];
                    
                    [tempArray addObject:phoneNumberString];
                    
                    [phoneNumbersDic setObject:tempArray forKey:labelName];
                    
                    [tempArray release];
                }
                else
                {
                    [phoneNumbersDic setObject:[NSArray arrayWithObjects:phoneNumberString, nil]
                                        forKey:labelName];
                }
            }
        }
        
        // Add on 2012-03-07
        CFRelease(phoneNumbers);
        
        return [phoneNumbersDic autorelease];
    }
    
    return nil;
}

#pragma mark -
#pragma mark Get person email address(es)
- (NSDictionary *)personEmail
{
    if(_record)
    {
        ABMultiValueRef emailAddresses = ABRecordCopyValue(_record, kABPersonEmailProperty);
        
        NSMutableDictionary* emailAddressesDic = [[NSMutableDictionary alloc] init];
        
        int nEmailAddressesCount = ABMultiValueGetCount(emailAddresses);
        
        for(int i = 0; i < nEmailAddressesCount; i++)
        {
            NSString* labelName = [self personLabelName:(NSString*)ABMultiValueCopyLabelAtIndex(emailAddresses, i)];
            NSString* emailString = (NSString*)ABMultiValueCopyValueAtIndex(emailAddresses, i);
            
            if(![labelName isEqualToString:@"其他:"])
            {
                [emailAddressesDic setObject:emailString forKey:labelName];
            }
            else
            {
                if([[emailAddressesDic allKeys] containsObject:@"其他:"])
                {
                    NSMutableArray* tempArray = [[NSMutableArray alloc] init];
                    
                    [tempArray addObjectsFromArray:[emailAddressesDic objectForKey:labelName]];
                    
                    [tempArray addObject:emailString];
                    
                    [emailAddressesDic setObject:tempArray forKey:labelName];
                    
                    [tempArray release];
                }
                else
                {
                    [emailAddressesDic setObject:[NSArray arrayWithObjects:emailString, nil]
                                          forKey:labelName];
                }
            }
        }
        
        SAFE_CFRELEASE(emailAddresses)
        
        return [emailAddressesDic autorelease];
    }
    return nil;
}

#pragma mark -
#pragma mark Change person label to Chinese name
- (NSString *)personLabelName:(NSString*)labelName
{
	if([labelName isEqualToString:@"_$!<Mobile>!$_"])
    {
		return MOBILE_LABEL;
    }
	else if([labelName isEqualToString:@"iPhone"])
		return IPHONE_LABEL;
	else if([labelName isEqualToString:@"_$!<Home>!$_"]) // For phone and email
		return HOME_LABEL;
	else if([labelName isEqualToString:@"_$!<Work>!$_"]) // For phone and email
		return WORK_LABEL;
	else if([labelName isEqualToString:@"_$!<Main>!$_"])
		return MAIN_LABEL;
	else if([labelName isEqualToString:@"_$!<HomeFAX>!$_"])
		return HOMEFAX_LABEL;
	else if([labelName isEqualToString:@"_$!<WorkFAX>!$_"])
		return WORKFAX_LABEL;
	else if([labelName isEqualToString:@"_$!<Pager>!$_"])
		return PAGER_LABEL;
	else if([labelName isEqualToString:@"_$!<Other>!$_"]) // For phone and email
		return OTHER_LABEL;
	else 
		return @":";
}

- (void)dealloc
{   
    SAFE_CFRELEASE(_record)
    
    [super dealloc];
}

@end
